<template>
  <div class="page-wapper">
    <!-- <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-calendar"></i> 发布日报
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div> -->
    <el-row :gutter="20">
      <!-- 左边部分 -->
      <el-col :xs="24" :span="12" :class="{ mb_s: isPhone }">
        <el-form ref="formRef" :rules="rules" :model="form" label-width="90px">
          <el-form-item label="模块名称" prop="moduleIds">
            <ProjectModuleCascade
              ref="projectModuleCascadeRef"
              @change="changeModuleIds"
            />
          </el-form-item>

          <!-- <el-form-item label="分隔符" prop="splitChar">
            <el-input v-model="form.splitChar"></el-input>
          </el-form-item> -->

          <el-form-item label="工作内容" prop="reportText">
            <el-input
              type="textarea"
              rows="10"
              v-model="form.reportText"
            ></el-input>
          </el-form-item>

          <el-form-item label="工作进度" prop="workProgress">
            <el-slider v-model="form.workProgress"></el-slider>
          </el-form-item>

          <el-form-item label="快捷选进度">
            <el-button size="small" @click="form.workProgress = 50"
              >50%</el-button
            >
            <el-button size="small" @click="form.workProgress = 90"
              >90%</el-button
            >
            <el-button size="small" @click="form.workProgress = 100"
              >100%</el-button
            >
          </el-form-item>

          <!-- <el-form-item label="日期时间">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.date1"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item> -->

          <el-form-item class="align_center">
            <el-button
              type="primary"
              size="small"
              @click="onAddMethod"
              :loading="addBtnLoading"
            >
              添加
            </el-button>
            <el-button size="small" @click="onResetMethod">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <!-- 右边部分 -->
      <el-col :xs="24" :span="12" v-loading="showBoxLoading">
        <div class="date_title mb_s">{{ todayDateTime }}</div>
        <div class="show_box mb_m">
          <ul v-if="todayReportList.length">
            <li v-for="(item, i) in todayReportList" :key="i" class="list_item">
              <!-- <div
                class="bg_progress"
                :style="{ width: item.workProgress + '%' }"
              ></div> -->

              <div class="item_content">
                <span class="seq">{{ i + 1 }}</span>
                <span class="split_char">{{ item.splitChar }}</span>
                <span v-for="(cell, j) in item.moduleNamesArr" :key="j"
                  >【{{ cell }}】</span
                >
                <span>{{ item.reportText }}&nbsp;&nbsp;</span>
                <span>{{ item.workProgress }}%&nbsp;&nbsp;</span>
                <span>{{ item.reportName }}</span>
              </div>

              <div class="delete_btn" @click="deleteReportMethod(item)">
                <delete-filled
                  style="
                    width: 1.2em;
                    height: 1.2em;
                    margin-right: 14px;
                    color: #f56c6c;
                  "
                />
              </div>
            </li>
          </ul>
          <div v-else class="color_gray">新的一天，开始今天的工作吧~</div>
        </div>

        <div class="align_center">
          <el-button type="primary" size="small" @click="copyMethod"
            >复制全部</el-button
          >
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  reactive,
  ref,
  getCurrentInstance,
  onMounted,
  computed,
  nextTick,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import moment from "moment";
import ProjectModuleCascade from "../../components/ProjectModuleCascade.vue";

const initFormData = () => {
  return {
    id: "",
    moduleIds: "",
    moduleNames: "",
    splitChar: "、",
    reportText: "",
    workProgress: 0,
  };
};

export default {
  name: "reportSave",
  components: { ProjectModuleCascade },
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const router = useRouter();
    const store = useStore();

    const userInfo = computed(() => store.state.user.userInfo);

    const formRef = ref(null);
    const addBtnLoading = ref(false);
    const showBoxLoading = ref(false);

    const form = reactive(initFormData());

    const rules = {
      reportText: [
        { required: true, message: "请输入工作内容", trigger: "blur" },
      ],
      workProgress: [
        { required: true, message: "请选择工作进度", trigger: "blur" },
      ],
    };

    const projectModuleCascadeRef = ref(null);

    // 今天添加的日程数据
    const todayReportList = ref([]);
    const todayDateTime = ref("");

    onMounted(() => {
      getToDayReportList();
      todayDateTime.value = moment().format("YYYY-MM-DD");
    });

    // 选择模块
    const changeModuleIds = ({ moduleIds, moduleNames }) => {
      console.log("changeModuleIds => ", { moduleIds, moduleNames });
      if (moduleIds && moduleNames) {
        form.moduleIds = moduleIds;
        form.moduleNames = moduleNames;
      }
    };

    // 获取今天添加的日程数据
    const getToDayReportList = () => {
      const startDateTime = moment()
        .startOf("day")
        .format("YYYY-MM-DD HH:mm:ss");
      const endDateTime = moment().endOf("day").format("YYYY-MM-DD HH:mm:ss");
      $api.report
        .getToDayReportList({
          current: 1,
          size: 999,
          startDateTime: startDateTime,
          endDateTime: endDateTime,
        })
        .then((res) => {
          todayReportList.value = res.data.list.map((item) => {
            return {
              ...item,
              moduleNamesArr: item.moduleNames
                .split("|")
                .filter((item) => item),
              moduleIdsArr: item.moduleIds.split("|").filter((item) => item),
            };
          });
        })
        .catch((err) => {
          console.error("getToDayReportList error: ", err);
        });
    };

    // 立即添加
    const onAddMethod = () => {
      // 需要检查有没有填写真实姓名
      if (!userInfo.value.truename) {
        ElMessageBox.confirm(
          `你还没有填写你的【姓名】，需要现在去填写吗？`,
          "提示",
          { type: "warning" }
        )
          .then(() => {
            router.push({
              name: "user",
              params: {
                truename: true,
              },
            });
          })
          .catch(() => {});
        return;
      }
      formRef.value.validate((valid) => {
        if (valid) {
          addBtnLoading.value = true;
          if (!form.splitChar) {
            form.splitChar = "、";
          }
          $api.report
            .addReport(form)
            .then((res) => {
              ElMessage.success("添加成功！");
              getToDayReportList();
              // 清空日报内容输入框
              form.reportText = "";
              // 清空进度条
              form.workProgress = 0;
            })
            .catch((err) => {
              console.error("addReport error: ", err);
            })
            .finally(() => {
              addBtnLoading.value = false;
            });
        } else {
          return false;
        }
      });
    };

    // 重置
    const onResetMethod = () => {
      // 重置表单校验
      formRef.value && formRef.value.resetFields();
      // 清空级联
      nextTick(() => {
        projectModuleCascadeRef.value && projectModuleCascadeRef.value.clear();
      });
      // 重置表单数据
      Object.keys(form).forEach((item) => {
        form[item] = initFormData()[item];
      });
    };

    // 删除单个内容
    const deleteReportMethod = (row) => {
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除【${
          row.reportText.length > 10
            ? row.reportText.slice(0, 10) + "..."
            : row.reportText
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          deleteTableData([row.id]);
        })
        .catch(() => {});
    };

    // 删除内容
    const deleteTableData = (ids) => {
      showBoxLoading.value = true;
      $api.report
        .deleteReport({
          ids,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          getToDayReportList();
        })
        .catch((err) => {
          console.error("deleteReport error: ", err);
        })
        .finally(() => {
          showBoxLoading.value = false;
        });
    };

    // 复制功能
    const copyMethod = () => {
      let content = "";
      content += todayDateTime.value + "\n";
      todayReportList.value.forEach((item, index) => {
        content += index + 1;
        content += item.splitChar;
        item.moduleNamesArr.forEach((cell, j) => {
          content += `【${cell}】`;
        });
        content += item.reportText + "  ";
        content += `${item.workProgress}%  `;
        content += `(${item.reportName})`;
        content += "\n";
      });
      // console.log('content = ' + content)
      if (!document.queryCommandSupported("copy")) {
        ElMessage.warning("浏览器不支持此功能！");
        return;
      }
      const textarea = document.createElement("textarea");
      textarea.value = content;
      textarea.readOnly = "readOnly";
      document.body.appendChild(textarea);
      textarea.select();
      textarea.setSelectionRange(0, content.length);
      const result = document.execCommand("copy");
      if (result) {
        ElMessage.success("已复制到剪切板！");
      } else {
        ElMessage.error("复制失败！");
      }
      textarea.remove();
    };

    return {
      rules,
      formRef,
      form,
      userInfo,
      addBtnLoading,
      showBoxLoading,
      todayReportList,
      todayDateTime,
      copyMethod,
      onAddMethod,
      onResetMethod,
      deleteReportMethod,
      projectModuleCascadeRef,
      changeModuleIds,
    };
  },
};
</script>
<style lang="css" scoped>
.left_content {
  width: 50%;
}
.right_content {
  flex: 1;
  height: 100%;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
  border-left: 2px dashed #dcdfe6;
}
.show_box {
  flex: 1;
  overflow: hidden auto;
}

.date_title {
  font-size: 18px;
  line-height: 22px;
}

ul {
  list-style: none;
}

.list_item {
  position: relative;
  margin-bottom: 4px;
  border-radius: 4px;
  overflow: hidden;
  padding: 6px 10px;
  padding-right: 35px;
}

.list_item .bg_progress {
  background-color: #e6a23c;
  height: 100%;
}

.list_item .item_content {
  line-height: 22px;
  font-size: 16px;
  color: #333;
  width: 100%;
  word-break: break-all;
}

.list_item:hover {
  background-color: #f5f5f5;
}
.list_item:hover .delete_btn {
  display: block;
}
.delete_btn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-44%);
  display: none;
  cursor: pointer;
  z-index: 10;
}
</style>
